from lxml import etree
 
# 解析 XML 文件
tree = etree.parse("books.xml")
root = tree.getroot()
 
# 打印根元素
print(f"根元素：{root.tag}")
 
# 遍历书籍
for book in root.findall("book"):
    print(f"\nBook ID: {book.get('id')}")
    print(f"Title: {book.find('title').text}")
    print(f"Author: {book.find('author').text}")
    print(f"Year: {book.find('year').text}")


# 查找所有书名
titles = tree.xpath("//title")
for title in titles:
    print(f"书名：{title.text}")
 
# 查找特定年份的书籍
books_2023 = tree.xpath("//book[year='2023']")
for book in books_2023:
    print(f"2023年的书名：{book.find('title').text}")